<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { getMyInfo, getOpenidAndLogin, getPhoneNumber, registerAndLogin } from '@/api/me'

const { setToken, setUserInfo } = useUserStore()
const isAgree = ref(false)
const isRegister = ref(false)
const loginFormRef = ref(null)
const loginForm = ref({
  name: '',
  phone: '',
  code: '',
})
const loginFormRules = {
  name: [{ required: true, message: '请输入昵称' }],
}

// 拉起获取手机号
async function onGetPhoneNumber({ detail: { code, errMsg } }) {
  try {
    if (!errMsg.includes('ok'))
      throw new Error('请授权手机号')

    await uni.showLoading({ title: '请稍后' })
    const { result: { phoneNumber } } = await getPhoneNumber(code)
    uni.hideLoading()

    loginForm.value.phone = phoneNumber

    await onValidate()
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

// 获取用户基本信息
async function onGetUserInfo() {
  try {
    const { result } = await getMyInfo()
    setUserInfo(result)
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

// 登录
async function onLogin() {
  if (!isAgree.value) {
    await uni.showToast({ icon: 'none', title: '请阅读并同意用户协议和隐私条款', duration: 2000 })
    return
  }

  try {
    await uni.showLoading({ title: '请稍后' })
    const { code } = await uni.login()
    const { success, result } = await getOpenidAndLogin(code)
    uni.hideLoading()

    if (!success) {
      loginForm.value.code = code
      isRegister.value = true
    }
    else {
      setToken(result.token)
      await onGetUserInfo()
      await uni.showToast({ icon: 'success', title: '登录成功' })
    }
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

// 注册
async function onRegister() {
  try {
    await uni.showLoading({ title: '请稍后' })
    const { success, message, result } = await registerAndLogin(loginForm.value)
    uni.hideLoading()

    if (!success) {
      throw new Error(message)
    }
    else {
      setToken(result.token)
      await onGetUserInfo()
      await uni.showToast({ icon: 'success', title: '注册成功' })
    }
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

// 表单校验
function onValidate() {
  loginFormRef.value.validate().then(({ valid }) => {
    if (valid)
      onRegister()
  })
}

function gotoAgree(type) {
  uni.navigateTo({
    url: `/pages/me/view/agreement?type=${type}`,
  })
}
</script>

<template>
  <view>
    <main class="px-3 mt-5">
      <view class="mb-4.5 text-[#666] center flex-col">
        <image class="h-120 w-120" src="../../static/image/me/default-avatar.png" />
      </view>
      <view v-if="isRegister" class="bg-white rounded-xl shadow overflow-hidden">
        <nut-config-provider :theme-vars="{ cellBoxShadow: 'none' }">
          <nut-form ref="loginFormRef" :model-value="loginForm" :rules="loginFormRules">
            <nut-form-item prop="name">
              <nut-input v-model="loginForm.name" placeholder="请输入昵称" type="text" />
            </nut-form-item>
            <nut-form-item>
              <view class="py-4">
                <nut-button
                  block
                  custom-color="linear-gradient(to right, #F89201, #F83600)"
                  open-type="getPhoneNumber"
                  @getphonenumber="onGetPhoneNumber"
                >
                  确认
                </nut-button>
              </view>
            </nut-form-item>
          </nut-form>
        </nut-config-provider>
      </view>
      <view v-else class="bg-white rounded-xl shadow overflow-hidden">
        <view class="px-4 py-12.5">
          <nut-button
            block
            custom-color="linear-gradient(to right, #F89201, #F83600)"
            @click="onLogin"
          >
            快速登录
          </nut-button>
          <view class="pt-8 text-28 text-sm">
            <nut-checkbox v-model="isAgree">
              <view class="text-[#999] flex whitespace-nowrap">
                <text>已阅读并同意</text>
                <text class="text-[#3E7CDE]" @click.stop="gotoAgree('user')">
                  《用户协议》
                </text>
                <text>
                  和
                </text>
                <text class="text-[#3E7CDE]" @click.stop="gotoAgree('private')">
                  《隐私条款》
                </text>
              </view>
            </nut-checkbox>
          </view>
        </view>
      </view>
    </main>
  </view>
</template>
